Compiler optimizations for vector instructions

ABSTRACT

An optimizing compiler includes a vector optimization mechanism that optimizes vector instructions by eliminating one or more vector element reverse operations. The compiler can generate code that includes multiple vector element reverse operations that are inserted by the compiler to account for a mismatch between the endian bias of the instruction and the endian preference indicated by the programmer or programming environment. The compiler then analyzes the code and reduces the number of vector element reverse operations to improve the run-time performance of the code.

RELATED APPLICATIONS

This patent application is a non-provisional of provisional applicationU.S. Ser. No. 62/036,741 filed Aug. 13, 2014 entitled “OPTIMIZING VECTORACCESSES ON AN ENDIAN-BASED MULTI-ENDIAN INSTRUCTION SET ARCHITECTURE”,and is also related to U.S. Ser. No. 14/576,391 filed on Dec. 19,2014entitled “COMPILER METHOD FOR GENERATING INSTRUCTIONS FOR VECTOROPERATIONS ON A MULTI-ENDIAN PROCESSOR” and is also related to U.S. Ser.No. 14/576,710 filed on Dec. 19,2014 entitled “COMPILER METHOD FORGENERATING INSTRUCTIONS FOR VECTOR OPERATIONS IN A MULTI-ENDIANINSTRUCTION SET”, all of which are incorporated herein by reference.

BACKGROUND

1. Technical Field

This disclosure generally relates to computer systems, and morespecifically relates to compilers that generate executable code forcomputer systems.

2. Background Art

Computer systems have evolved into extremely sophisticated devices, andcomputer systems may be found in many different settings. Dramaticadvances in both hardware and software (e.g., computer programs) havedrastically improved the performance of computer systems. Modernsoftware has become very complex when compared to early computerprograms. Many modern computer programs have from tens of thousands tomany millions of instructions. The execution time (and hence,performance) of a computer program is very closely related to the numberand complexity of instructions that are executed as the computer programruns. Thus, as the size and complexity of computer programs increase,the execution time of the computer program increases as well.

Unlike early computer programs, modern computer programs are typicallywritten in a high-level language that is easy to understand by a humanprogrammer. Special software tools known as compilers take thehuman-readable form of a computer program, known as “source code”, andconvert it into “machine code” or “object code” instructions that may beexecuted by a computer system. Because a compiler generates the streamof machine code instructions that are eventually executed on a computersystem, the manner in which the compiler converts the source code toobject code affects the execution time of the computer program.

The execution time of a computer program, especially complex computerprograms, is a function of the number, arrangement and type ofinstructions within the computer program. Many different optimizationshave been developed so the code produced by compilers has betterrun-time performance.

BRIEF SUMMARY

An optimizing compiler includes a vector optimization mechanism thatoptimizes vector instructions by eliminating one or more vector elementreverse operations. The compiler can generate code that includesmultiple vector element reverse operations that are inserted by thecompiler to account for a mismatch between the endian bias of theinstruction and the endian preference indicated by the programmer orprogramming environment. The compiler then analyzes the code and reducesthe number of vector element reverse operations to improve the run-timeperformance of the code.

The foregoing and other features and advantages will be apparent fromthe following more particular description, as illustrated in theaccompanying drawings.

BRIEF DESCRIPTION OF THE SEVERAL VIEWS OF THE DRAWING(S)

The disclosure will be described in conjunction with the appendeddrawings, where like designations denote like elements, and:

FIG. 1 is a block diagram of an apparatus that includes a vectoroptimization mechanism in a compiler;

FIG. 2 is a block diagram illustrating how a byte array is stored inlittle endian and big endian systems;

FIG. 3 is a block diagram illustrating how a word array is stored inlittle endian and big endian systems;

FIG. 4 is a flow diagram of a method for defining vector optimizationrules for a compiler to optimize vector instructions;

FIG. 5 is a flow diagram of a method for a compiler to optimize vectorinstructions according to defined vector instruction processing rules;

FIG. 6 is a diagram of a table that shows an example of the vectorinstruction processing rules shown in FIG. 1;

FIG. 7 is a diagram showing a sample snippet of code processed by acompiler;

FIG. 8 is a diagram showing instructions generated by the compiler as aresult of processing the instructions in FIG. 7;

FIG. 9 is a block diagram illustrating a first possible compileroptimization for the instructions in FIG. 8;

FIG. 10 is a block diagram illustrating a second possible compileroptimization for the instructions in FIG. 9;

FIG. 11 shows the table 600 in FIG. 6 with an added vector optimizationrule;

FIG. 12 is a diagram showing a sample snippet of code processed by acompiler;

FIG. 13 is a diagram showing instructions generated by the compiler as aresult of processing the instructions in FIG. 12;

FIG. 14 is a block diagram illustrating a compiler optimization for theinstructions in FIG. 13;

FIG. 15 shows the table 600 in FIGS. 6 and 11 with localized vectoroptimization rules;

FIG. 16 is a diagram showing a sample snippet of code processed by acompiler;

FIG. 17 is a diagram showing instructions generated by the compiler as aresult of processing the instructions in FIG. 16;

FIG. 18 is a block diagram showing a sample snippet of code processed bya compiler;

FIG. 19 is a diagram showing instructions generated by the compiler as aresult of processing the instructions in FIG. 18;

FIG. 20 is a block diagram showing endian-biased instructions withvector element reverse operations;

FIG. 21 is a diagram showing conversion of the multiple instructions inFIG. 20 to a single instruction;

FIG. 22 is a block diagram showing a sample snippet of code processed bya compiler;

FIG. 23 is a diagram showing instructions generated by the compiler as aresult of processing the instructions in FIG. 22; and

FIG. 24 is a flow diagram of a specific method for the optimizingcompiler shown in FIG. 1 to perform vector optimizations based on vectoroptimization rules.

DETAILED DESCRIPTION

Exploiting opportunities for parallel computation is very important formodern computing systems. One of the most common opportunities forparallel computation arises when the same operation is to be performedon an array (or “vector”) of homogeneous data elements. Today'sprocessor instruction set architectures (ISAs) usually include a set ofsingle-instruction, multiple-data (SIMD) instructions that can operateon 2, 4, 8, 16, or 32 values simultaneously. SIMD instructions areexamples of what are more broadly termed vector instructions as usedherein. For example, the Power ISA currently defines the Vector AddFloating-Point (vaddfp) instruction. This instruction operates on128-bit vector registers, whose contents are interpreted as four 32-bitfloating-point values. The corresponding values in each input registerare added together and placed in the corresponding position in theoutput register. Thus four additions are performed using a singleinstruction.

Another aspect of today's processors is the concept of “endianness.”This refers to how the processor stores bytes of a multi-byte value inmemory. For example, a 64-bit integer in a machine register contains 8bytes, arranged from most-significant byte (MSB) containing the bitsrepresenting the largest portions of the integer, to theleast-significant byte (LSB) containing the bits representing thesmallest portions of the integer. On a so-called Big Endian (BE)architecture, the same value is stored in memory with byte 0 containingthe MSB, and byte 7 containing the LSB. On a so-called Little Endian(LE) architecture, the value is stored in memory with byte 0 containingthe LSB, and byte 7 containing the MSB. These two methods arose forhistorical performance reasons that no longer matter a great deal,except that in today's world we must deal with these two incompatibleviews of memory.

BE and LE systems typically view values differently in vector registersas well. When an array of four 32-bit values is loaded into a 128-bit BEvector register, the zeroth element of the array occupies the mostsignificant bytes, while the third element of the array (zero-basedindexing) occupies the least significant bytes. When the same array isloaded into a 128-bit LE vector register, the zeroth element of thearray occupies the least significant bytes, while the third element ofthe array occupies the most significant bytes. These are considered tobe the “natural element order” for BE and LE memory models. The contentsof each 4-byte element are represented in the same fashion on both BEand LE architectures, with the sign bit of the floating-point valueplaced in the most significant bit of the element.

Some ISAs (Power and ARM, for example) are designed to operate either inBig Endian mode or in Little Endian mode. In the Power ISA, the endianmode is selected with a control bit in the machine state register (MSR).Thus the same instructions are available to carry out computationregardless of endianness. This is of no concern for instructions such as“vaddfp” described above, where the computation is performed uniformlyon all elements of the instruction's input and output registers.However, when an instruction implicitly or explicitly refers to theelement numbering within a vector register, the numbering that isnatural for one endianness is unnatural for the other.

In some cases, an ISA may provide instructions to facilitate maintainingelements in vectors using a particular element order, regardless of theendian mode specified by the programmer. For example, the Load VSXVector Doubleword*2 Indexed (lxvd2x) instruction in the Power ISAspecifically loads elements into a vector register using the BE naturalelement order, whether or not the machine is using the BE memory modelor the LE memory model. Similarly, the Store VSX Vector Doubleword*2Indexed (stxvd2x) reverses this transformation, storing to memory asthough the elements in the vector register use the BE natural elementorder. Using these instructions allows a programmer to ignore the actualendian memory model in use, for a subset of data types and instructions.Data within each element are formatted in memory based on the selectedendian model, e.g., in accordance with the mode selected by MSR[LE].

An instruction that regards vector elements in vector registers using BEnatural element order is said to have a BE vector element endian bias.Conversely, an instruction that regards vector elements in vectorregisters using LE natural element order is said to have an LE vectorelement endian bias. When the preponderance of vector instructions in anISA have the same endian bias, this is referred to as the inherentendian bias of the ISA.

FIGS. 2 and 3 show examples of how data arrays may be represented inmemory, using big-endian and little-endian data representation, and howthey may be represented in vector registers, using l→r and r→l elementordering. In FIG. 2, an array of bytes containing {0, 1, . . . , 15} isshown. Since each vector element is one byte long, the little-endian(LE) and big-endian (BE) representations in memory are identical, withthe first element stored in the lowest address. Using r→l elementordering (LE), the first element is stored in the least significant byte(LSB) of the vector register; while using l→r element ordering (BE), thefirst element is stored in the most significant byte (MSB).

FIG. 3 shows representations for an array of 4-byte integers, containing{0x00010203, 0x04050607, 0x08090a0b, 0x0c0d0e0f}. In memory, elementsappear in ascending address order for both BE and LE, but the byte orderwithin each element differs. In registers, the opposite is true: theelements appear from right to left using r→l order (LE) and from left toright using l→r order (BE), but within each element the byte ordering isidentical. Thus, we see the 4-byte integer stored in the leastsignificant four bytes of the LE register are the same order, namely 00,01, 02, 03 as the 4-byte integer stored in the most significant fourbytes of the BE register. The order that changes is the order ofelements, not the order of bytes within the elements.

The two related applications cited herein disclose ways for a compilerto insert one or more vector element reverse operations into a computerprogram to account for a mismatch in endian bias. The addition of vectorelement reverse operations reduces performance of the code, but assurescorrect operation. The disclosure herein is directed to a compiler thatanalyzes the code that includes the added vector element reverseoperations and eliminates one or more of the vector element reverseoperations to improve performance of the code.

Referring to FIG. 1, a computer system 100 is one suitableimplementation of a server computer system that includes a compiler witha vector optimization mechanism as described in more detail below.Server computer system 100 is an IBM POWER8 computer system. However,those skilled in the art will appreciate that the disclosure hereinapplies equally to any computer system, regardless of whether thecomputer system is a complicated multi-user computing apparatus, asingle user workstation, or an embedded control system. As shown in FIG.1, computer system 100 comprises one or more processors 110, a mainmemory 120, a mass storage interface 130, a display interface 140, and anetwork interface 150. These system components are interconnectedthrough the use of a system bus 160. Mass storage interface 130 is usedto connect mass storage devices, such as local mass storage device 155,to computer system 100. One specific type of local mass storage device155 is a readable and writable CD-RW drive, which may store data to andread data from a CD-RW 195.

Main memory 120 preferably contains data 121, an operating system 122,source code 123, an intermediate representation 124, a compiler 125, andmachine code 128. Data 121 represents any data that serves as input toor output from any program in computer system 100. Operating system 122is a multitasking operating system. There are three differentrepresentations of a computer program in FIG. 1, namely the high-levelsource code 123, the intermediate representation 124 that is generatedby a front-end compiler from the source code 123, and the machine code128 that is generated by a back-end compiler from the intermediaterepresentation 124. The vector optimization mechanism 126 disclosedherein could be implemented within a front-end compiler, within aback-end compiler, or different aspects of the vector optimizationmechanism 126 could be implemented in both a front-end compiler and aback-end compiler. The compiler 125 thus could represent either afront-end compiler, a back-end compiler, or a full compiler thatincludes a front-end and a back-end. The compiler 125 includes thevector optimization mechanism 126 that optimizes vector instructionsaccording to defined vector optimization rules 127.

Note the source code 123, intermediate representation 124, compiler 125,and machine code 128 are all shown residing in memory 120 for theconvenience of showing all of these elements in one drawing. One skilledin the art will appreciate that this is not the normal mode of operationfor most compilers. A front-end compiler processes source code 123 andgenerates therefrom intermediate representation 124. This processing mayoccur on a computer system separate from computer system 100. A back-endcompiler processes intermediate representation 124 and generatestherefrom machine code 128, which may also occur on a separate computersystem. Compiler 125 could be a front-end compiler, or could be acompiler that includes both a front end and a back end. In the extreme,source code 123 could reside on a first computer system and a front-endcompiler could reside on a second computer system. The front-endcompiler could read the source code 123 from the first computer system,generate the intermediate representation 124, and store the intermediaterepresentation 124 on a third computer system. A back-end compiler couldbe executed on a fourth computer system, which reads the intermediaterepresentation 124 from the third computer system, and generatestherefrom machine code 128, which could be written to a fifth computersystem. This simple example shows that the preferred embodimentsexpressly extend to any suitable configuration and number of computersystems to accomplish the front-end and back-end compiling. The“apparatus” described herein and in the claims expressly extends to amultiple computer configuration, as described by the example above. Inaddition, the vector optimization mechanism 126 can include differentportions implemented in different parts of the compiler.

Computer system 100 utilizes well known virtual addressing mechanismsthat allow the programs of computer system 100 to behave as if they onlyhave access to a large, contiguous address space instead of access tomultiple, smaller storage entities such as main memory 120 and localmass storage device 155. Therefore, while data 121, operating system122, source code 123, intermediate representation 124, compiler 125, andmachine code 128 are shown to reside in main memory 120, those skilledin the art will recognize that these items are not necessarily allcompletely contained in main memory 120 at the same time. It should alsobe noted that the term “memory” is used herein generically to refer tothe entire virtual memory of computer system 100, and may include thevirtual memory of other computer systems coupled to computer system 100.

Processor 110 may be constructed from one or more microprocessors and/orintegrated circuits. Processor 110 executes program instructions storedin main memory 120. Main memory 120 stores programs and data thatprocessor 110 may access. When computer system 100 starts up, processor110 initially executes the program instructions that make up operatingsystem 122. Processor 110 also executes the compiler 125. Processor 110preferably includes a vector processing unit (VPU) 112 and multiplevector registers 114. The VPU 112 and vector registers 114 allow theprocessor to execute Single Instruction Multiple Data (SIMD)instructions, which are examples of vector instructions discussedherein.

Although computer system 100 is shown to contain only a single processorand a single system bus, those skilled in the art will appreciate that acompiler as described herein may be practiced using a computer systemthat has multiple processors and/or multiple buses. In addition, theinterfaces that are used preferably each include separate, fullyprogrammed microprocessors that are used to off-load compute-intensiveprocessing from processor 110. However, those skilled in the art willappreciate that these functions may be performed using I/O adapters aswell.

Display interface 140 is used to directly connect one or more displays165 to computer system 100. These displays 165, which may benon-intelligent (i.e., dumb) terminals or fully programmableworkstations, are used to provide system administrators and users theability to communicate with computer system 100. Note, however, thatwhile display interface 140 is provided to support communication withone or more displays 165, computer system 100 does not necessarilyrequire a display 165, because all needed interaction with users andother processes may occur via network interface 150.

Network interface 150 is used to connect computer system 100 to othercomputer systems or workstations 175 via network 170. Network interface150 broadly represents any suitable way to interconnect electronicdevices, regardless of whether the network 170 comprises present-dayanalog and/or digital techniques or via some networking mechanism of thefuture. Network interface 150 preferably includes a combination ofhardware and software that allows communicating on the network 170.Software in the network interface 150 preferably includes acommunication manager that manages communication with other computersystems 175 via network 170 using a suitable network protocol. Manydifferent network protocols can be used to implement a network. Theseprotocols are specialized computer programs that allow computers tocommunicate across a network. TCP/IP (Transmission ControlProtocol/Internet Protocol) is an example of a suitable network protocolthat may be used by the communication manager within the networkinterface 150.

The present invention may be a system, a method, and/or a computerprogram product. The computer program product may include a computerreadable storage medium (or media) having computer readable programinstructions thereon for causing a processor to carry out aspects of thepresent invention.

The computer readable storage medium can be a tangible device that canretain and store instructions for use by an instruction executiondevice. The computer readable storage medium may be, for example, but isnot limited to, an electronic storage device, a magnetic storage device,an optical storage device, an electromagnetic storage device, asemiconductor storage device, or any suitable combination of theforegoing. A non-exhaustive list of more specific examples of thecomputer readable storage medium includes the following: a portablecomputer diskette, a hard disk, a random access memory (RAM), aread-only memory (ROM), an erasable programmable read-only memory (EPROMor Flash memory), a static random access memory (SRAM), a portablecompact disc read-only memory (CD-ROM), a digital versatile disk (DVD),a memory stick, a floppy disk, a mechanically encoded device such aspunch-cards or raised structures in a groove having instructionsrecorded thereon, and any suitable combination of the foregoing. Acomputer readable storage medium, as used herein, is not to be construedas being transitory signals per se, such as radio waves or other freelypropagating electromagnetic waves, electromagnetic waves propagatingthrough a waveguide or other transmission media (e.g., light pulsespassing through a fiber-optic cable), or electrical signals transmittedthrough a wire.

Computer readable program instructions described herein can bedownloaded to respective computing/processing devices from a computerreadable storage medium or to an external computer or external storagedevice via a network, for example, the Internet, a local area network, awide area network and/or a wireless network. The network may comprisecopper transmission cables, optical transmission fibers, wirelesstransmission, routers, firewalls, switches, gateway computers and/oredge servers. A network adapter card or network interface in eachcomputing/processing device receives computer readable programinstructions from the network and forwards the computer readable programinstructions for storage in a computer readable storage medium withinthe respective computing/processing device.

Computer readable program instructions for carrying out operations ofthe present invention may be assembler instructions,instruction-set-architecture (ISA) instructions, machine instructions,machine dependent instructions, microcode, firmware instructions,state-setting data, or either source code or object code written in anycombination of one or more programming languages, including an objectoriented programming language such as Smalltalk, C++ or the like, andconventional procedural programming languages, such as the “C”programming language or similar programming languages. The computerreadable program instructions may execute entirely on the user'scomputer, partly on the user's computer, as a stand-alone softwarepackage, partly on the user's computer and partly on a remote computeror entirely on the remote computer or server. In the latter scenario,the remote computer may be connected to the user's computer through anytype of network, including a local area network (LAN) or a wide areanetwork (WAN), or the connection may be made to an external computer(for example, through the Internet using an Internet Service Provider).In some embodiments, electronic circuitry including, for example,programmable logic circuitry, field-programmable gate arrays (FPGA), orprogrammable logic arrays (PLA) may execute the computer readableprogram instructions by utilizing state information of the computerreadable program instructions to personalize the electronic circuitry,in order to perform aspects of the present invention.

Aspects of the present invention are described herein with reference toflowchart illustrations and/or block diagrams of methods, apparatus(systems), and computer program products according to embodiments of theinvention. It will be understood that each block of the flowchartillustrations and/or block diagrams, and combinations of blocks in theflowchart illustrations and/or block diagrams, can be implemented bycomputer readable program instructions.

These computer readable program instructions may be provided to aprocessor of a general purpose computer, special purpose computer, orother programmable data processing apparatus to produce a machine, suchthat the instructions, which execute via the processor of the computeror other programmable data processing apparatus, create means forimplementing the functions/acts specified in the flowchart and/or blockdiagram block or blocks. These computer readable program instructionsmay also be stored in a computer readable storage medium that can directa computer, a programmable data processing apparatus, and/or otherdevices to function in a particular manner, such that the computerreadable storage medium having instructions stored therein comprises anarticle of manufacture including instructions which implement aspects ofthe function/act specified in the flowchart and/or block diagram blockor blocks.

The computer readable program instructions may also be loaded onto acomputer, other programmable data processing apparatus, or other deviceto cause a series of operational steps to be performed on the computer,other programmable apparatus or other device to produce a computerimplemented process, such that the instructions which execute on thecomputer, other programmable apparatus, or other device implement thefunctions/acts specified in the flowchart and/or block diagram block orblocks.

The flowchart and block diagrams in the Figures illustrate thearchitecture, functionality, and operation of possible implementationsof systems, methods, and computer program products according to variousembodiments of the present invention. In this regard, each block in theflowchart or block diagrams may represent a module, segment, or portionof instructions, which comprises one or more executable instructions forimplementing the specified logical function(s). In some alternativeimplementations, the functions noted in the block may occur out of theorder noted in the figures. For example, two blocks shown in successionmay, in fact, be executed substantially concurrently, or the blocks maysometimes be executed in the reverse order, depending upon thefunctionality involved. It will also be noted that each block of theblock diagrams and/or flowchart illustration, and combinations of blocksin the block diagrams and/or flowchart illustration, can be implementedby special purpose hardware-based systems that perform the specifiedfunctions or acts or carry out combinations of special purpose hardwareand computer instructions.

A compiler as disclosed and claimed herein includes a vectoroptimization mechanism that optimizes vector instructions by eliminatingone or more vector element reverse operations. The compiler can generatecode that includes multiple vector element reverse operations that areinserted by the compiler to account for a mismatch between the endianbias of the instruction and the endian preference indicated by theprogrammer or programming environment. The compiler then analyzes thecode and reduces the number of vector element reverse operations toimprove the run-time performance of the code.

Referring to FIG. 4, method 400 defines one or more vector optimizationrules for processing an intermediate representation of the code (step410). The vector optimization rules defined in step 410 correspond tovector optimization rules 127 shown in FIG. 1. A method 500 shown inFIG. 5 analyzes the intermediate representation generated from thesource code (step 510). When the intermediate representation has novector instructions (step 520=NO), method 500 is done. When theintermediate representation has one or more vector instructions (step520=YES), but the vector instruction(s) do not satisfy the vectoroptimization rules (step 530=NO), method 500 is done. When the vectorinstruction(s) satisfy the vector optimization rules (step 530=YES), thevector instruction(s) are optimized according to the vector optimizationrules (step 540). The optimization in step 540 can include, for example,eliminating one or more vector element reverse operations. Variousexamples are now presented to illustrate different optimizations thatcould be performed in step 540.

An example of a vector optimization rule 127 shown in FIG. 1 is shown inFIG. 6. For all vector copy operations, the unneeded vector elementreverse (vreverse) operations in the intermediate representation areeliminated, as shown at 610.

The disclosure and claims herein provide a way for a compiler tomitigate the performance cost of added vector element reverseoperations, such as vector element reverse operations added by thecompiler after vector load instructions and before vector storeinstructions. In this disclosure, we refer to any vector loadinstruction (whether biased-endian like “lxvd2x”, or natural-endian like“lvx”) as a vload, and similarly refer to any vector store instructionas a vstore. We will also refer to any operation that reverses theelements of a vector register as a vreverse, and to an instruction thatcopies the contents of one register into another as a vcopy. However,the methods described herein are equally applicable regardless of thekinds of loads, stores, and reverse operations employed.

A “vreverse operation” generally refers to a series of one or moreinstructions that reverses the order of elements in a vector register.There are different vreverse operations for each element size (1 byte, 2bytes, 4 bytes, 8 bytes, 16 bytes, etc.). An ISA may, but need not,include machine instructions that map directly to vreverse operations ofevery size. Alternatively, more general instructions (such as permutesor shuffles) may be used instead.

In the most preferred implementation, there are preferably differentvector element reverse instructions for each different element size thatcan be specified in an instruction set. Thus, if a system definesvectors with element sizes of bytes, halfwords (2 bytes), words (4bytes) and doublewords (8 bytes), there will be a different vectorelement reverse instruction for each of these. For example, a bytevector element reverse instruction could be vreverse. A halfword vectorelement reverse instruction could be vreverse_hw. A word vector elementreverse instruction could be vreverse w. A double word vector elementreverse instruction could be vreverse_dw. Of course, any suitable syntaxcould be used, and any suitable number of vector element reverseinstructions could be defined, depending on the element sizes defined bythe instruction set, whether currently known or developed in the future.For example, a quadword vector element reverse instruction could bedefined and vector element reverse instructions for elements larger thanquadwords could also be defined. For the simplicity of the examplesherein, the size of the vector element reverse instruction is notspecified, realizing that the size could vary as described above.

The compiler optimizations disclosed herein may be performed during anyappropriate stage of the compilation process in order to eliminate oneor more vreverse operations in the code. A compiler operates on one ormore intermediate representations of code, which may be organized invarious ways that may be more or less appropriate to a particularoptimization. For example, an intermediate representation may representexpressions in a tree or directed-acyclic graph (DAG) form, or may use avariant of three-address code. Of course, many more variations arepossible, whether currently known or developed in the future. Thisdisclosure applies regardless of the chosen intermediate representationand without regard to specific unimportant details of how theoptimizations are implemented.

In the simplest case, it is common for a vector to be copied from onememory location to another, such as shown in FIG. 7. Using variousmethods, including the methods disclosed in the two related application,the compiler could generate for the code in FIG. 7 the instructionsshown in FIG. 8, where t1, t2, and t3 are vector registers. The effectof each vreverse is to reverse the order of the elements in the vectorregister. We assume for this example the vreverse t2=t1 instruction wasadded by the compiler to reverse the order of the vector elements afterthe vload t1=a instruction, and the vreverse t3=t2 instruction was addedby the compiler to reverse the order of the vector elements before thevstore b=t3 instruction. Thus the first vreverse will reverse theelements, and the second vreverse will restore them to their originallocations. If the value of t2 is not used anywhere else, the compilermay replace the instructions shown in FIG. 8 with the instructions shownin FIG. 9. Then, standard compiler optimizations known as copypropagation and/or value numbering can reduce the instructions in FIG. 9to the instructions shown in FIG. 10. Note that all vreverse operationshave been removed, so there is now no performance penalty.

More specifically, an exemplary compiler performing an exemplarytranslation of the code of FIG. 7 described in conjunction with theserules may generate assembly code corresponding to FIG. 8 for alittle-endian environment in accordance with the instructions for POWER8as follows:

lxvd2x 0,0,4

xxpermdi 0,0,0,2

xxpermdi 0,0,0,2

stxvd2x 0,0,3

In accordance with one exemplary implementation of the presentinvention, when the optimizations described herein are performed, anexemplary compiler may generate code corresponding to FIG. 10 for alittle-endian environment in accordance with the POWER8 instruction setas follows:

lxvd2x 0,0,4

stxvd2x 0,0,3

Note that a code sequence where one vreverse operation feeds anothervreverse operation for elements of the same size can arise in othercontexts than a vector copy. For example, the optimization rules in rule620 of FIG. 11 may introduce such a code sequence. At any time such acode sequence is introduced, every use of the result of the secondvreverse operation may be replaced with the input to the first vreverseoperation, and the second vreverse operation may be removed. If theresult of the first vreverse operation is not used elsewhere, it mayalso be removed.

Recall that a vreverse operation may not be implemented as a singleinstruction. For example, the Power ISA implemented by the POWER8processor does not include single instructions corresponding to vreverseoperations for elements of size 1, 2, or 4 bytes. Consequently, a vectorload of a data type such as vector char, vector short, vector int, orvector float is often implemented using a sequence of a vector load oftwo doublewords followed by a permute that reverses the elements, and avector store of such a data type is often implemented using a sequenceof a vector store of two doublewords preceded by a permute that reversesthe elements.

Suppose a and b in FIG. 7 are of type vector signed int, rather thanvector signed long. In accordance with one embodiment, this may betranslated into a sequence similar to that of FIG. 8, but due to thelack of a suitable vreverse instruction for vector word elements, thegenerated sequence would be more expensive:

vload t1=a

vload rev_w=<control vector to reverse word elements>

vperm t2, t1, rev_w

vperm t3, t2, rev_w

vstore t3

As can be seen, this sequence requires an additional load of a vectorpermute control vector that instructs a permute instruction to reversethe word elements of a vector registers. Furthermore, using the POWER8instruction set, only a subset of the vector registers may be used toperform a vector permute instruction, which may lead to additionalregister copy instructions, data spills to memory, and so forth.

In accordance with one optimized embodiment, the vector word copysequence is translated into an intermediate representation which mayload words with an element order of element 1, element 0, element 3,element 2 (denoted hereafter by vload_w1032) and use a suitablebig-endian permutation (2,3,0,1) to create the “normal” little-endianorder (3,2,1,0), and the converse operations for a vector store. Thisprovides the following initial translation to an intermediaterepresentation:

vload_w1032 t1=a

vperm_w2301 t2=t1

vperm_w2301 t3=t2

vstore_w1032 b=t3

Advantageously, vload_w1032 may be implemented by an lxvd2x instruction,vperm_2301 may be implemented by an xxpermdi instruction, andvstore_w1032 may be implemented by an stxvd2x instruction. This yieldsthe following improved copy sequence:

lxvd2x 0,0,4

xxpermdi 0,0,0,2

xxpermdi 0,0,0,2

stxvd2x 0,0,3

Note that, although we are using it on a vector of words, vperm_w2301 isactually a vreverse operation for doublewords. Thus in accordance withthe teachings herein, since the first vperm_w2301 instruction feeds thesecond vperm_w2301 instruction, and the result of the first vperm_w2301instruction is not used elsewhere, the two vperm_w2301 instructions maybe removed as above, yielding:

vload_w1032 t1=a

vstore_w1032 b=t1

This final intermediate representation may then be translated to thefollowing code to copy a vector of word elements:

lxvd2x 0,0,4

stxvd2x 0,0,3

FIG. 11 shows the table 600 of vector optimization rules that includesan additional rule 620 that states that for computations where alloperations performed on input vectors are pure SIMD instructions,eliminate the unneeded vector element reverse operations in theintermediate representation. Suppose we have a computation where alloperations performed on the input vectors are pure SIMD instructions;that is, the instructions perform parallel computations on thecorresponding elements of all input vectors independently. In this case,the relative order of elements within the registers will not affect thefinal results as long as it is consistent, and we can avoid vreverseoperations for the entire sequence. A sample source statement is shownin FIG. 12. Letting vadd represent vector addition and vand representvector bit-wise AND, the compiler could generate the code shown in FIG.13, where t1 through t9 are vector registers. If the compiler recognizesthat none of the reversed values t2, t4, t5, t7, and t8 is used outsidethis sequence, then the entire sequence can be converted to theinstructions shown in FIG. 14. One way to implement this is to firstapply the rule from the example shown in FIGS. 18 and 19, below, to thevadd, then apply the same rule to the vand, and finally apply the rulefrom the example in FIGS. 7-10. Another possible implementation is toanalyze webs of computation where all sources originate from loads afterwhich vector element reverse operations have been added and all sinksflow into stores before which vector element reverse operations havebeen added. The former is simpler to implement and faster to optimize,while the latter is more general and can be performed on computationsthat contain loops. Any implementation in which the instructionsproducing intermediate results and other instructions consuming thoseintermediate results are identified can be used. Examples include thewell known Value Numbering, Value Propagation, Reaching Analysis,Instruction Generation Folding, and Peephole optimizations.

In another aspect of the present invention, using the POWER8 instructionset, the compiler may be presented with a variant of FIG. 13 thatoperates on a vector of single precision floating-point elements of4-byte size:

vload_w1032 t1=x

vperm_w2301 t2=t1

vload_w1032 t3=z

vperm_w2301 t4=t3

vadd_fp t5=t2, t4

vload_w1032 t6=w

vperm_w2301 t7=t6

vand_w t8=t5, t7

vperm_w2301 t9=t8

vstore_w1032 y=t9

In conjunction with the teachings herein, the compiler generates:

vload_w1032 t1=x

vload_w1032 t3=z

vadd_fp t5=t2, t4

vload_w1032 t6=w

vand_w t8=t5, t7

vstore_w1032 y=t9

The intermediate representation may then be translated into thefollowing machine instruction sequence on a POWER8 processor:

lxvd2x 0,0,4

lxvd2x 1,0,5

xvaddsp 0,0,1

lxvd2x 12,0,6

xxland 0,0,12

stxvd2x 0,0,9

A variant on the example in FIGS. 11-14 occurs when the compilerautomatically generates vector code from scalar code. This“auto-vectorization” optimization may be performed on loops over arrayelements or on straight-line sections of code that make references toadjacent array elements. The compiler can replace operations onindividual array elements with SIMD instructions that operate on severalelements in parallel.

When auto-vectorized code is generated, the same sort of transformationscan be made as shown in FIGS. 13 and 14. However, it may be easier insome cases for the compiler to recognize these cases. The compiler maygenerate special symbols or flags associated with vector loads andstores created for auto-vectorization, and thereby know that the vloadsand vstores that it generates need not have vreverses inserted.

Even when an entire expression may not be optimized as shown in FIGS.13-14, subexpressions may be optimized with localized rules. Examples oflocalized rules are shown at 630 in FIG. 15 to include unary operationsrules, binary operations rules, endian conversion rules, and loads ofliterals or named constants rules. Examples of each of these follow.

For some unary operations such as negate, the instructions in FIG. 16can be changed to the instructions in FIG. 17, or vice versa. While thisdoes not reduce the number of instructions, the changed order ofinstructions may result in making optimization possible that was notpossible before. For example, if a vector reverse operation preceded theunaryop y=x instruction, switching the order of the instructions asshown in FIG. 17 could result in two consecutive vreverse operations,which could then be optimized by removing the vreverse operations asshown in FIGS. 8-10. Even when the reversal does not allow eliminating avreverse operation, it may improve performance by allowing one or moreother instructions to use the result of the unary operation sooner.

For pure SIMD binary operations, the instructions shown in FIG. 18 couldbe reduced to the instructions shown in FIG. 19. Conversions betweennatural-endian loads/stores and biased-endian loads/stores are possiblegiven the correct vreverses for the type. For example, referring toFIGS. 20 and 21, an instruction lvx+vreverse4×4 can be converted tolvxw4x, where “vreverseNxS” represents reversal of a vector having Nelements, each of which has size S bytes. An instruction lvx+vreverse2×8can be converted to lxvd2x. An instruction vreverse4×4+stvx can beconverted to stvxw4x. An instruction vreverse2×8+stvx can be convertedto stvxd2x. Note that it may also be beneficial to make the reversetransformation, for example, converting a lxvd2x into a anlvx+vreverse2×8. If the lxvd2x is itself followed by a vreverse2×8, thiswill produce back-to-back vreverse2×8 instructions that can then beeliminated as shown in FIGS. 8-10.

For loads of literals or named constants, the two instructions shown inFIG. 22 can be converted to the one instruction shown in FIG. 23, where“vreverse(literal)” represents the vector literal with its elementsreversed in memory. In some cases the reverse transformation is alsouseful, to enable other transformations; for example, so that bothinputs to an add are vreverse operations.

As a general rule, combinations of vreverse with binary or unaryoperations should be transformed first, and combinations of vreversewith loads and stores should be transformed last, in order to maximizeother opportunities. These and other transformations may be used toreduce the number of vreverse operations added to the generated code.For instance, there are many rules specific to a particular instructionset architecture that may be applied to optimize combinations ofvreverse and other instructions. In some cases another pass over thenon-load or store instructions can find more opportunities.

Referring to FIG. 24, a method 2400 shows one possible method that couldbe performed by the compiler as described herein. The optimizationrequires pre-computation of def-use and use-def chains (step 2410). Thisis an industry-standard analysis to produce data structures thatrepresent register relationships between instructions. If an instructionI modifies (defines) a register R, then the def-use chain for (I,R)lists all instructions that consume that definition of R. Also, if aninstruction I makes use of a register R, then the use-def chain for(I,R) lists all instructions that could provide the definition of R thatI uses. In many optimizers, def-use and use-def chains are maintainedthroughout the optimization phases. In this case, step 2410 requires nowork. Otherwise, step 2410 performs this industry-standard analysis tomake the chains available.

Next, step 2420 is performed as follows. The compiler walks throughevery instruction in the intermediate representation of the currentfunction. For each instruction I, check whether I mentions a vectorregister. If not, continue to the next instruction. Otherwise, mark I as“relevant.” For each use of a register R in I, union {I} with eachinstruction in the use-def chain for (I,R). For each definition of aregister R in I, union {I} with each instruction in the def-use chainfor (I,R). If I is a load or store, record that information. If I is avreverse operation, record that as well. If I is not a vreverseoperation, determine whether it is swappable (is not sensitive toelement order) or swappable with special handling (is sensitive toelement order, but can be modified if its containing subgraph isoptimized). Note that an instruction can be both a load or a store, anda vector reverse that indicates a load or store like lxvd2x. If Icontains a register use that is live on entry to the function, recordthat information. If I defines a register that is live on exit from thefunction, record that information. When step 2420 is finished, therelevant instructions in the function have been partitioned into maximalsubgraphs of vector computation. Each subgraph has a representativeinstruction, as determined by the classic set-union algorithm.

At this point step 2430 is performed as follows. Walk through eachinstruction a second time. If anything about the instruction makes theweb not optimizable, record this fact in the representative instructionof its subgraph. This includes the instruction being marked live onentry or live on exit, a load or store that is not permuting (and is notswappable with special handling), a permuting load or store that is notaccompanied by a register swap, or an instruction that is not marked aseither a swap or swappable.

Next, step 2440 is performed as follows. Walk through each instruction athird time, looking for permuting loads and stores that are accompaniedby a vector element reverse operation, and whose representativeinstruction has not been marked as not optimizable. Mark theaccompanying vector element reverse operations for future removal.During the same pass, look for instructions that have been marked asswappable with special handling, and whose representative instructionhas not been marked as not optimizable. Perform the special handling forthese. Examples of special handling include changing the element numberon the instruction, such as for a vector-splat, vector-insert orvector-extract operation, changing the element number selectors in apermute or shuffle instruction, changing an instruction operating oneven elements, odd elements, upper elements or lower elements to theopposite, converting a non-permuting load or store into a permuting one,and swapping the elements in a constant vector.

Next, step 2450 is performed as follows. Walk through the instructions afourth time, looking for vector element reverse operations that havebeen marked for deletion, and replace each of them with a register copy.It is necessary to do this separately from step 2440 because a singleswap can be associated with more than one load or store due to otheroptimizations.

The claims and disclosure herein provide a compiler that includes avector optimization mechanism that optimizes vector instructions byeliminating one or more vector element reverse operations. The compilercan generate code that includes multiple vector element reverseoperations that are inserted by the compiler to account for a mismatchbetween the endian bias of the instruction and the endian preferenceindicated by the programmer or programming environment. The compilerthen analyzes the code and reduces the number of vector element reverseoperations to improve the run-time performance of the code.

One skilled in the art will appreciate that many variations are possiblewithin the scope of the claims. Thus, while the disclosure isparticularly shown and described above, it will be understood by thoseskilled in the art that these and other changes in form and details maybe made therein without departing from the spirit and scope of theclaims.

The invention claimed is:
 1. A computer-implemented method executed byat least one processor for processing a plurality of instructions in acomputer program, the method comprising: providing a computer programincluding a plurality of instructions that includes at least one vectoroperation; and processing the plurality of instructions to eliminate atleast one vector element reverse operation from the computer program toenhance run-time performance of the computer program by: recordingcharacteristics of vector instructions and forming subgraphs of relatedinstructions by analyzing def-use and use-def chains for the computerprogram in a first pass; determining whether any of the subgraphs cannotbe optimized in a second pass; identifying a computation in the computerprogram where all operations performed on input vectors are singleinstruction multiple data (SIMD) instructions and marking for removal atleast one vector element reverse operation that corresponds to thecomputation in a third pass; and deleting in a fourth pass the at leastone vector element reverse operation marked for removal in the thirdpass.
 2. The method of claim 1 further comprising: identifying in thethird pass a first vector element reverse operation and a second vectorelement reverse operation in the computer program, such that the resultof the first vector element reverse operation is the source of thesecond vector element reverse operation; and eliminating in the fourthpass at least one of the first and second vector element reverseoperations.
 3. The method of claim 1 further comprising: identifying aunary operation accompanied by at least one vector element reverseoperation; and changing order of instructions for the unary operationand the at least one vector element reverse operation.
 4. The method ofclaim 1 further comprising: identifying in the third pass a binaryoperation accompanied by at least one vector element reverse operation;and eliminating in the fourth pass the at least one vector elementreverse operation that accompanies the binary operation.
 5. The methodof claim 1 further comprising: identifying in the third pass a firstinstruction that specifies an endian load followed by a secondinstruction that performs a vector element reverse operation; andeliminating in the fourth pass the second instruction by converting thefirst instruction into a third instruction that specifies an endian loadthat does not require the second instruction.
 6. The method of claim 1further comprising: identifying in the third pass a first instructionthat is a vector element reverse operation that precedes a secondinstruction that is an endian store; and eliminating in the fourth passthe first instruction by converting the second instruction into a thirdinstruction that specifies an endian store that does not require thefirst instruction.
 7. The method of claim 1 further comprising:identifying in the third pass a first instruction that specifies avector load of a literal value followed by a second instruction that isa vector element reverse operation; and eliminating in the fourth passthe second instruction by reversing order of the elements in the literalvalue in the first instruction.
 8. A computer-implemented methodexecuted by at least one processor for processing a plurality ofinstructions in a computer program, the method comprising: providing acomputer program including a plurality of instructions that includes atleast one vector instruction; in a first pass, recording characteristicsof vector instructions and forming subgraphs of related instructions byanalyzing def-use and use-def chains for the computer program; in asecond pass, determining whether any of the subgraphs cannot beoptimized; in a third pass: identifying a first vector element reverseoperation and a second vector element reverse operation in the computerprogram, such that the result of the first vector element reverseoperation is the source of the second vector element reverse operation,and marking the first and second vector element reverse operations forremoval; identifying a computation in the computer program where alloperations performed on input vectors are single instruction multipledata (SIMD) instructions and marking at least one vector element reverseoperation that corresponds to the computation for removal; identifying aunary operation accompanied by at least one vector element reverseoperation and changing order of instructions for the unary operation andthe at least one vector element reverse operation; identifying a firstinstruction that specifies an endian load followed by a secondinstruction that performs a vector element reverse operation, andmarking the second instruction for removal by converting the firstinstruction into a third instruction that specifies an endian load thatdoes not require the second instruction; identifying a binary operationaccompanied by at least one vector element reverse operation and markingthe at least one vector element reverse operation that accompanies thebinary operation for removal; identifying a fourth instruction that is avector element reverse operation that precedes a fifth instruction thatis an endian store, and marking the fourth instruction for removal byconverting the fifth instruction into a sixth instruction that specifiesan endian store that does not require the fourth instruction; andidentifying a seventh instruction that specifies a vector load of aliteral value followed by an eighth instruction that is a vector elementreverse operation, and marking the eighth instruction for removal byreversing order of the elements in the literal value in the seventhinstruction; and in a fourth pass, deleting the vector element reverseoperations marked for removal in the third pass.